package com.sevenwonders.util;

import java.util.Collection;
import java.util.Map;

import com.sevenwonders.SettingsActivity;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.preference.PreferenceManager;

public class Helper {

    private Helper() {
        throw new AssertionError();
    }

    public static boolean isEmpty(Object obj) {
        if (obj instanceof CharSequence) {
            CharSequence cs = (CharSequence) obj;
            return cs.length() == 0;
        } else if (obj instanceof Collection) {
            Collection<?> c = (Collection<?>) obj;
            return c.isEmpty();
        } else if (obj instanceof Map) {
            Map<?, ?> m = (Map<?, ?>) obj;
            return m.isEmpty();
        }

        return obj == null;
    }

    public static boolean isEmpty(Object[] array) {
        return array == null || array.length == 0;
    }

    public static String getPreference(Context context, String key, String defaultValue) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(key, defaultValue);
    }
    
    public static boolean getBooleanPreference(Context context, String key, boolean defaultValue) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getBoolean(key, defaultValue);
    }

    public static int updateOrientation(Activity activity, int lockOrientation) {
        int currLockOrientation = Integer.parseInt(getPreference(activity, SettingsActivity.KEY_LOCK_ORIENTATION, String.valueOf(-1)));

        if (currLockOrientation != lockOrientation || currLockOrientation != activity.getRequestedOrientation()) {
            lockOrientation = currLockOrientation;

            if (lockOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                if (activity.getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                    // You need to check if your desired orientation isn't already set because setting orientation restarts your Activity which takes long
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
            } else if (lockOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                if (activity.getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
            } else {
                if (activity.getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_SENSOR) {
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
                }
            }
        }

        return lockOrientation;
    }
}
